package com.wtc.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtility {
    private static SqlSessionFactory sqlSessionFactory = null;

    static {

        try {
            //定义主配置文件名称
            String resource = "mybatis-config.xml";
            //读取主配置文件地址
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //创建sqlSessionFactory对象
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession() {
        //获取SqlSession
        SqlSession sqlSession = null;

        if (sqlSessionFactory != null) {
            sqlSession = sqlSessionFactory.openSession();
        }

        return sqlSession;
    }
}
